package com.example.sunran.servlet;

import com.example.sunran.utils.FileUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class UploadFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<String> pList = new ArrayList<>();
        List<FileItem> list = null;
        String filename=null;

        try {
            list = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        boolean uploadSucc= true;
        for(FileItem item : list) {
            //如果fileitem中封装的是普通输入项的数据
            if (item.isFormField()) {
                String value = item.getString("UTF-8");
                pList.add(value);
                continue;
            } else {//如果fileitem中封装的是上传文件
                InputStream stream = item.getInputStream();
                filename = item.getName();
                try {
                    FileUtils.saveFile(filename,stream);
                } catch (IOException e) {
                    uploadSucc = false;
                }
            }
        }
        resp.setContentType("text/html;charset=utf-8");
        if (uploadSucc) {
            resp.getOutputStream().write("上传成功！".getBytes());
        }else{
            resp.getOutputStream().write("上传失败！".getBytes());
        }

    }
}
